<?php
class ControllerSdtclassUploadImage extends Controller {
	public function index() {
	    // 初始化
		$this->load->language('tool/upload');
		$json = array();

		if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
			// 重新整理文件名去掉一些符号
			$filename = basename(preg_replace('/[^a-zA-Z0-9\.\-\s+]/', '', html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8')));

			// 判断文件名长度
			if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 64)) {
				$json['error'] = $this->language->get('error_filename');
			}

			// 判断扩展名
			$allowed = array();

			$extension_allowed = array('jpg','jpeg','gif','png','bmp','tiff','svg');

			foreach ($extension_allowed as $filetype) {
				$allowed[] = trim($filetype);
			}

			if (!in_array(strtolower(substr(strrchr($filename, '.'), 1)), $allowed)) {
				$json['error'] = $this->language->get('error_filetype');
			}

			// 判断文件类型
			$allowed = array();

			$mime_allowed = array('image/png','image/jpeg','image/gif','image/bmp', 'image/tiff','image/svg+xml');

			foreach ($mime_allowed as $filetype) {
				$allowed[] = trim($filetype);
			}

			if (!in_array($this->request->files['file']['type'], $allowed)) {
				$json['error'] = $this->language->get('error_filetype');
			}

			// 判断是否PHP文件
			$content = file_get_contents($this->request->files['file']['tmp_name']);

			if (preg_match('/\<\?php/i', $content)) {
				$json['error'] = $this->language->get('error_filetype');
			}

			// 返回上传错误
			if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
				$json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
			}
		} else {
			$json['error'] = $this->language->get('error_upload');
		}

		if (!$json) {
		    // 文件名加16个随机符填充。
			$file = token(16).'.'.$filename;
			// 判断是否有用户登陆，来初始化文件夹。
			if($this->customer->getId()) {
			    $upload_dir = 'upload/user_id_'.$this->customer->getId().'/';
            }else{
                $upload_dir = 'upload/other/';
            }
            // 如果当心文件夹太多也可以同年月
            // $upload_dir = date('Y-m').'/';
            // 自己创建upload文件夹即可，少个判断，提高性能。
            if (!is_dir(DIR_IMAGE .$upload_dir)) {
                mkdir(DIR_IMAGE .$upload_dir, 0755);
                chmod(DIR_IMAGE .$upload_dir, 0755);
            }

			// 上传文件
			move_uploaded_file($this->request->files['file']['tmp_name'], DIR_IMAGE.$upload_dir . $file);

			// 返回文件相对路径和成功信息。
			$json['code'] = $upload_dir.$file;
			$json['success'] = $this->language->get('text_upload');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
		//  www.sdtclass.com 小草 提供
	}
}